import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs/internal/BehaviorSubject';

import { LoginUser } from 'src/app/shared/models';
import { ROLE_LIST } from './role';

@Injectable({providedIn: 'root'})
export class AuthService {
    private _currentUser: BehaviorSubject<LoginUser> = new BehaviorSubject(null);

    get currentUser$() {
        return this._currentUser;
    }

    get currentUser() {
        return this._currentUser.value || JSON.parse(localStorage.getItem('currentUser'));
    }

    setCurrentUser(currentUser: LoginUser) {
        localStorage.setItem('currentUser', JSON.stringify(currentUser));
        this._currentUser.next(currentUser);
    }

    clearUserInfo() {
        localStorage.removeItem('currentUser');
        this._currentUser.next(null);
    }

    isAuthorized(roles: string[]) {
        return this.isValidRole(roles);
    }

    filterFolderByRole(folders: Array<any>) {
        return folders.filter(foldItem => {
            if (!foldItem.roles) {
                return true;
            } else {
                return this.isAuthorized(foldItem.roles);
            }
        });
    }

    getInitRedirectPageByRole() {
        const currentRole = this.currentUser.roleCode;
        if ([...ROLE_LIST.allManage, ...ROLE_LIST.allSec].includes(currentRole)) {
            return '/layout/monitor';
        } else if ([...ROLE_LIST.allDev].includes(currentRole)) {
            return '/layout/project-management/projects';
        } else {
            return '/layout/assets-management/container';
        }
    }

    private isValidRole(roles: string[]): boolean {
        const currentRole = this.currentUser.roleCode;
        return roles.some(roleItem => {
            return currentRole === roleItem;
        });
    }
}
